import json
import Agently
import requests
from bs4 import BeautifulSoup
from logger import logger
from lib.read_yaml import read_yaml
from lib.ResponseHandlers import ResponseHandlers

env = read_yaml('./env.yaml')
global_variables = read_yaml('./global_variables.yaml')

agent_factory = (
    Agently.AgentFactory(is_debug=env["DEBUG"])
        .set_settings("current_model", env["MODEL_ADAPTER"])
        .set_settings(f"model.{ env['MODEL_ADAPTER'] }.auth", { "api_key": env["API_KEY"] })
        .set_settings(f"model.{ env['MODEL_ADAPTER'] }.url", env["BASE_URL"])
        .set_settings(f"model.{ env['MODEL_ADAPTER'] }.options", env["MODEL_OPTIONS"])
)

if global_variables:
    for key, value in global_variables.items():
        agent_factory.set_global_variable(key, value)

if "PROXY" in env:
    agent_factory.set_settings("proxy", env["PROXY"])

response_handlers = ResponseHandlers(env)
response_handlers.scan(env["SCAN_PATH"])

def route(data, write_message):
    handler = response_handlers.get(data["event"])
    if handler:
        response_handlers.check(data["event"], data["data"])
        return handler(data["data"], agent_factory=agent_factory, write_message=write_message)
    else:
        raise Exception(f"Event is not supported: '{ data['event'] }'.")